package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.events.Event;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

/**
 * CLassName: CacheClient
 * Description:
 * Author: wuzhixiang
 * Date: 2024-11-01 9:50
 * Version: 1.0
 */
@Component
@Slf4j
public class CacheClient {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

//    public CacheClient(StringRedisTemplate stringRedisTemplate) {
//        this.stringRedisTemplate = stringRedisTemplate;
//    }

    /**
     * 将数据写入redis中
     *
     * @param key
     * @param value
     * @param time
     * @param timeUnit
     */
    public void set(String key, Object value, Long time, TimeUnit timeUnit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, timeUnit);
    }

    /**
     * 解决缓存击穿问题，设置逻辑过期时间
     *
     * @param key
     * @param value
     * @param time
     * @param timeUnit
     */
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit timeUnit) {
        //设置逻辑过期时间
        RedisDate redisDate = new RedisDate();
        redisDate.setData(value);
        redisDate.setExpireTime(LocalDateTime.now().plusSeconds(timeUnit.toSeconds(time)));
        //写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisDate));
    }

    /**
     * 解决缓存穿透
     *
     * @param keyPrefix  key前缀
     * @param id         要传的id
     * @param clazz      返回的类型
     * @param dbFallback 查询数据库的语句
     * @param time       时间大小
     * @param timeUnit   时间单位
     * @param <T>
     * @param <ID>
     * @return
     */
    public <T, ID> T queryWithPassThrough(String keyPrefix, ID id, Class<T> clazz, Function<ID, T> dbFallback,
                                          Long time, TimeUnit timeUnit) {
        String key = keyPrefix + id;
        //1 从redis查询商铺缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        //2 判断是否存在
        if (StrUtil.isNotBlank(json)) {
            //3 存在，直接返回
            return JSONUtil.toBean(json, clazz);//将json格式转成shop对象
        }
        //判断命中的是否是空值
        if ("".equals(json)) {
            return null;
        }
        //4 不存在，根据id查询数据库
        T t = dbFallback.apply(id);
        if (t == null) {
            // 将空值写入redis
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            //5 不存在，返回错误
            return null;
        }
        //6 存在，写入redis
        this.setWithLogicalExpire(key, t, time, timeUnit);
        //7 返回
        return t;
    }

    private static final ExecutorService CACHE_REBUIDE_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 解决缓存击穿，设置逻辑过期
     * @param keyPrefix
     * @param id
     * @param clazz
     * @param dbFallback
     * @param time
     * @param timeUnit
     * @return
     * @param <T>
     * @param <ID>
     */
    public <T,ID> T queryWithLogicalExpire(String keyPrefix, ID id, Class<T> clazz, Function<ID, T> dbFallback,
                                           Long time, TimeUnit timeUnit) {
        String key = keyPrefix + id;
        //1 从redis查询商铺缓存
        String Json = stringRedisTemplate.opsForValue().get(key);
        //2 判断是否存在
        if (StrUtil.isBlank(Json)) {
            //3 存在，直接返回
            return null;//将json格式转成shop对象
        }
        //4 命中，需要先把json反序列化为对象
        RedisDate redisDate = JSONUtil.toBean(Json, RedisDate.class);
        //Shop shop = (Shop) redisDate.getData();
        T t = JSONUtil.toBean((JSONObject) redisDate.getData(), clazz);
        LocalDateTime expireTime = redisDate.getExpireTime();
        //5 判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //5.1 未过期，直接返回店铺信息
            return t;
        }
        //5.2 过期，需要缓存重建
        //6 缓存重建
        //6.1 获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        //6.2 判断是否获取锁成功
        if (tryLock(lockKey)) {
            //6.3 成功，开启独立线程，实现缓存重建
            CACHE_REBUIDE_EXECUTOR.submit(() -> {
                try {
                    //1 重建缓存
                    //1.1 查询数据库
                    T t1 = dbFallback.apply(id);
                    //1.2 写入redis
                    this.setWithLogicalExpire(key, t1, time, timeUnit);
                    //this.saveShop2Redis(id, 20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //释放锁
                    unLock(lockKey);
                }
            });
        }
        //6.4 返回过期的商铺信息
        return t;
    }

    /**
     * 拿锁
     *
     * @param key
     * @return
     */
    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 释放锁
     *
     * @param key
     */
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }
}
